
#include "Stack-BinTree.h"


PBTree BuyNewNode()
{
	PBTree newNode = (PBTree)malloc(sizeof(BTree));
	if (newNode == NULL) {
		perror("Fail to malloc for BTreeNode(NULL):");
		exit(-1);
	}
	newNode->left = NULL;
	newNode->right = NULL;
	return newNode;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

bool StackEmpty(PStack S)
{
	return S->top == NULL;
}

int StackSize(PStack S)
{
	int count = 0;
	PStackNode cur = S->top;
	while (cur) {
		++count;
		cur = cur->next;
	}
	return count;
}

void StackPrint(PStack S)
{
	assert(S);
	bool flag = true;
	PStackNode cur = S->top;
	while (cur) {
		flag = false;
		printf("%c", cur->val);
		cur = cur->next;
		if (cur)
			printf(" -> ");
	}
	if (flag)
		printf("Nothing at all!");
	printf("\n");
}

PStack StackCreate()
{
	PStack S = (PStack)malloc(sizeof(Stack));
	if (S == NULL) {
		perror("Fail to malloc for Stack(NULL):");
		exit(-1);
	}
	S->top = NULL;
	return S;
}


void StackDestroy(PStack* pS)
{
	assert(pS && *pS);
	PStackNode cur = (*pS)->top, tmp = NULL;
	while (cur) {
		tmp = cur;
		cur = cur->next;
		free(tmp);
	}
	free(*pS);
	*pS = NULL;
}

void StackPush(PStack S, SDataType x)
{
	assert(S);
	PStackNode newNode = (PStackNode)malloc(sizeof(StackNode));
	if (newNode == NULL) {
		perror("Fail to malloc for StackNode(NULL):");
		return;
	}
	newNode->val = x;
	newNode->next = S->top;
	S->top = newNode;
}

void StackPop(PStack S)
{
	assert(S);
	if (StackEmpty(S)) {
		printf("The stack has nothing!\n");
		return;
	}
	PStackNode tmp = S->top;
	S->top = S->top->next;
	free(tmp);
}

SDataType StackTop(PStack S)
{
	return S->top->val;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

bool StackEmpty(PStack2 S)
{
	return S->top == NULL;
}

int StackSize(PStack2 S)
{
	int count = 0;
	PStackNode2 cur = S->top;
	while (cur) {
		++count;
		cur = cur->next;
	}
	return count;
}

PStack2 StackCreate2()
{
	PStack2 S = (PStack2)malloc(sizeof(Stack2));
	if (S == NULL) {
		perror("Fail to malloc for Stack(NULL):");
		exit(-1);
	}
	S->top = NULL;
	return S;
}


void StackDestroy(PStack2* pS)
{
	assert(pS && *pS);
	PStackNode2 cur = (*pS)->top, tmp = NULL;
	while (cur) {
		tmp = cur;
		cur = cur->next;
		free(tmp);
	}
	free(*pS);
	*pS = NULL;
}

void StackPush(PStack2 S, SDataType2 x)
{
	assert(S);
	PStackNode2 newNode = (PStackNode2)malloc(sizeof(StackNode2));
	if (newNode == NULL) {
		perror("Fail to malloc for StackNode(NULL):");
		return;
	}
	newNode->val = x;
	newNode->next = S->top;
	S->top = newNode;
}

void StackPop(PStack2 S)
{
	assert(S);
	if (StackEmpty(S)) {
		printf("The stack has nothing!\n");
		return;
	}
	PStackNode2 tmp = S->top;
	S->top = S->top->next;
	free(tmp);
}

SDataType2 StackTop(PStack2 S) 
{
	return S->top->val;
}
